var express = require("express"); //引入express 模块
var expressWs = require('express-ws');
var http = require('http')

var app = express(); //创建服务器 
const fs = require('fs');
const zlib = require('zlib');
// const compression = require('compression');  //引入compression模块
var bodyParser = require('body-parser') // node.js 中间件，用于处理 JSON, Raw, Text 和 URL 编码的数据。
var upload = require('./router/upload')// 使用路由功能
var birds = require('./router/birds')// 使用路由功能
var sendMail = require('./router/mailer')// 使用路由功能
var crypto = require('./router/crypto')// 使用加密功能 
var getApi = require('./router/getApi')// get请求模块
var postApi = require('./router/postApi')// get请求模块
var putApi = require('./router/putApi')// put请求模块 
var gzipApi = require('./router/gzipApi')// gzipApi请求模块  
var distscheduleApi = require('./router/distschedule-api')// distschedule-api请求模块   
var redirectApi = require('./router/redirectApi')// redirectApi请求模块   
var deleteApi = require('./router/deleteApi')// deleteApi请求模块    timeouteApi
var timeoutApi = require('./router/timeoutApi')// timeoutApi请求模块     
var cookieApi = require('./router/cookieApi')// cookieApi请求模块      
var contenttypeApi = require('./router/contenttypeApi')// contenttypeApi请求模块     
var websocketApi = require('./router/websocketApi')// websocketApi请求模块     
var http2Api = require('./router/http2Api')// http2Api请求模块     
var responseApi = require('./router/responseApi')// responseApi 请求模块     
var chunkuploadApi = require('./router/chunkuploadApi')// chunkuploadApi 请求模块    




//设置跨域访问
app.all("*", function (req, res, next) {
  console.log('<==============================================================> ')
  const data = {
    protocol: req.protocol, // http or htts
    hostname: req.hostname, // baidu.com
    ip: req.ip, // 127.0.0.1
    originalUrl: req.originalUrl, // /test
    method: req.method, // GET or POST
    baseUrl: req.baseUrl,
    path: req.path, // /test
    // route: req.route, // 路由信息
    params: req.params, // 参数{}
    body: req.body, // 请求主体，依赖body-parser 中间件
    query: req.query // 通过参数传递的 如 /test?name=1
  }

  console.log('发现一次请求: ', new Date().toLocaleString())
  console.log('请求的信息', data)
  // // 服务器允许被那些origin访问。，*或者www.example.com
  // res.header("Access-Control-Allow-Origin", "*") 
  // // 预设支持的方法
  // res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE")
  // // 预检将在正式请求的headers字段中出现的首部信息，以下这些特定的首部是一直允许的：Accept, Accept-Language, Content-Language, Content-Type
  // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  console.log('开始next')
  next();
});


var port = 9527; //设置端口9527
var hostName = "10.0.4.4"; //设置主机名127.0.0.1 localhost

// var server = app.listen(port, hostName, function() {
//   var host = server.address().address;
//   var port = server.address().port;

//   console.log(`服务器运行在http://${host}:${port}`)

//   let downloadPath = './public/download/test.txt'
//     let tempPath = './public/download/test.txt.gz'
//     let isExsit = fs.existsSync(tempPath);
//     console.log('zdy-----isExsit------>' + isExsit)
//     if (!isExsit) {
//       gzip(downloadPath)
//   }
// });
var server = http.createServer(app);
expressWs(app, server);
server.listen(port, hostName, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log(`服务器运行在http://${host}:${port}`)

  let downloadPath = './public/download/test.txt'
  let tempPath = './public/download/test.txt.gz'
  let isExsit = fs.existsSync(tempPath);
  console.log('zdy-----isExsit------>' + isExsit)
  if (!isExsit) {
    gzip(downloadPath)
  }
});


function gzip($src) {
  console.log('zdy-----stat $src ------>' + $src)
  fs.stat($src, function (err, stats) {
    console.log('zdy-----stat err ------>' + err)
    console.log('zdy----- stats ------>' + stats.isFile())
    if (stats.isFile()) {
      let rs = fs.createReadStream($src);
      //zlib.createGzip()创建一个gzip转换流，是一个可读可写流。
      //通过管道将数据读取出来写入gzip流，然后又通过管道写入一个文件流中
      let newPath = $src + '.gz';
      console.log('zdy-----$dst ------>' + newPath)
      fs.writeFile(newPath, '', 'utf-8', function (err) {
        if (!err) {
          rs.pipe(zlib.createGzip()).pipe(fs.createWriteStream(newPath));
        }
      });

    }
  });
}


/****************************************************************************************************
                          网站请求信息
****************************************************************************************************/
app.use('/upload', upload)// 使用路由中间件
app.use('/birds', birds)// 使用路由中间件
app.use('/sendMail', sendMail)// 发送邮件模块
app.use('/crypto', crypto)// 使用加密模块
app.use('/getApi', getApi)// getApi 请求模块
app.use('/postApi', postApi)// postApi 请求模块
app.use('/putApi', putApi)// putApi 请求模块 
app.use('/gzipApi', gzipApi)// gzipApi 请求模块  
app.use('/distscheduleApi', distscheduleApi)// distschedule-api 请求模块  
app.use('/redirectApi', redirectApi)// redirectApi 请求模块  
app.use('/deleteApi', deleteApi)// deleteApi 请求模块 
app.use('/timeoutApi', timeoutApi)// timeoutApi 请求模块  
app.use('/cookieApi', cookieApi)// cookieApi 请求模块   
app.use('/contenttypeApi', contenttypeApi)// contenttypeApi 请求模块    
app.use('/websocketApi', websocketApi)// websocketApi 请求模块    
app.use('/http2Api', http2Api)// http2Api 请求模块    
app.use('/responseApi', responseApi)// responseApi 请求模块    
app.use('/chunkuploadApi', chunkuploadApi)// chunkuploadApi 请求模块  


app.use(bodyParser.urlencoded({ extended: true }))// 解析post提交的数据为默认方式 application/x-www-form-urlencoded
app.use(bodyParser.json());// 解析post提交的数据为json格式
app.use(express.text());// 解析post提交的数据为json格式

// expressWs(app);

// app.get("/", function(req, res) {
//   res.send('服务器已成功启动！');
// });

// app.get("/test", function(req, res) {
//   res.send({
//     data: {
//       protocol: req.protocol, // http or htts
//       hostname: req.hostname, // baidu.com
//       ip: req.ip, // 127.0.0.1
//       originalUrl: req.originalUrl, // /test
//       method: req.method, // GET or POST
//       baseUrl: req.baseUrl,
//       path: req.path, // /test
//       route: req.route, // 路由信息
//       params: req.params, // 参数{}
//       body: req.body, // 请求主体，依赖body-parser 中间件
//       query: req.query // 通过参数传递的 如 /test?name=1
//     },
//     emessage: "成功",
//     statusCode:1
//   })
// });

// app.post("/test",function(req, res){
//   res.send({
//     data: {
//       protocol: req.protocol, // http or htts
//       hostname: req.hostname, // baidu.com
//       ip: req.ip, // 127.0.0.1
//       originalUrl: req.originalUrl, // /test
//       method: req.method, // GET or POST
//       baseUrl: req.baseUrl,
//       path: req.path, // /test
//       route: req.route, // 路由信息
//       params: req.params, // 参数{}
//       body: req.body, // 请求主体，依赖body-parser 中间件
//       query: req.query // 通过参数传递的 如 /test?name=1
//     },
//     emessage:"成功",
//     statusCode: 1
//   })
// })
